package com.desaysv.svview.loading;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.desaysv.svview.R;

/**
 * @author linzi
 * @date 2022-11-16
 */
public class LoadingDialog extends Dialog {
    private static LoadingDialog mDialog;
    private View mView=null;
    private ObjectAnimator mObj=null;
    private LoadingDialog(@NonNull Context context) {
        super(context);
        init();
    }
    private void init(){
        mView= LayoutInflater.from(getContext()).inflate(R.layout.layout_loading,null);
        setContentView(mView);
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        ImageView ivLoad=mView.findViewById(R.id.ivLoading);
        mObj = ObjectAnimator.ofFloat(ivLoad, "rotation", 0f, 360f);
        mObj.setDuration(3000);
        mObj.setRepeatCount(ValueAnimator.INFINITE);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(mObj!=null&&mObj.isStarted()) {
                    mObj.end();
                }
            }
        });
        setOnShowListener(new OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                if(mObj!=null&&!mObj.isStarted()) {
                    mObj.start();
                }
            }
        });
    }
    public static void show(Context context){
        if(mDialog==null){
            mDialog=new LoadingDialog(context);
        }
        if(!mDialog.isShowing()){
            mDialog.show();
        }
    }
    public static void hideLoading(){
        if(mDialog!=null&&mDialog.isShowing()){
            mDialog.dismiss();
        }
    }
}
